package com.zhiyun.notifier.service;

import com.zhiyun.notifier.auto.AutoConfig;
import com.zhiyun.notifier.client.DingTalkRobotClient;
import com.zhiyun.notifier.constant.ApplicationEvent;
import com.zhiyun.notifier.props.DingProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(AutoConfig.class)
@EnableConfigurationProperties(DingProperties.class)
@ConditionalOnProperty(
        prefix = "notifier.ding",
        name = "enable",
        havingValue = "true"
)
public class DingNotifier implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private DingTalkRobotClient dingTalkRobotClient;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        dingTalkRobotClient.sendAppEventMessage(ApplicationEvent.UP);
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                dingTalkRobotClient.sendAppEventMessage(ApplicationEvent.DOWN);
            }
        }));
    }
}
